<?php

namespace App\Repositories;


use App\Exceptions\BasicException;
use Illuminate\Support\Facades\DB;
use App\Enums\ErmEnum;
use Illuminate\Support\Facades\Redis;
use App\Enums\RedisKeyEnum;

//引入hash

class ErmWhiteRepository
{

    /*自动加白*/
    public function autoAddWhite()
    {
        $ermPayIdModel = app("model_erm_pay_id");
        $ermPublicListModel = app("model_erm_public_list");

        /*连续充值用户*/
        $user_res = $ermPayIdModel
            ->selectRaw('t1.user_id,t1.pay_id')
            ->from($ermPayIdModel->getTable() . ' as t1')
            ->join($ermPublicListModel->getTable() . ' as t2', 't1.user_id', '=', 't2.user_id')
            ->where(['t2.type' => ErmEnum::PUBLIC_TYPE, ['t1.continuity_num', '>=', ErmEnum::WHITE_PAY_ID_NUM]])
            ->groupBy('t1.user_id')
            ->get()->toArray();

        /*白名单用户*/
        foreach ($user_res as $k => $v) {
            $is_white = $ermPayIdModel
                ->selectRaw('t1.user_id,t1.pay_id')
                ->from($ermPayIdModel->getTable() . ' as t1')
                ->join($ermPublicListModel->getTable() . ' as t2', 't1.user_id', '=', 't2.user_id')
                ->where(['t2.type' => ErmEnum::WHITE_TYPE, 't1.pay_id' => $v['pay_id']])
                ->get()->toArray();
            if ($is_white) {
                /*加入白名单*/
                app('repo_erm_public_list')->joinListWay($v['user_id'], ErmEnum::WHITE_TYPE, '自动加白:连续' . ErmEnum::WHITE_PAY_ID_NUM . '次支付id相同');
            }
        }

    }

    /**
     * 超时自动去白
     *
     * @return void
     */
    public function autoRemoveExpireWhite()
    {
        // 白名单过期用户
        $whiteList = app("model_erm_white_list")
            ->select('id', 'user_id')
            ->where('expire_time', '<', time())
            ->where('expire_time', '>', 0)
            ->get();
        foreach ($whiteList as $k => $v) {
            $is_white = app('model_erm_public_list')->where(['user_id' => $v['user_id'], 'type' => ErmEnum::WHITE_TYPE])->first();
            if ($is_white) {
                app('repo_erm_public_list')->joinListWay($v['user_id'], ErmEnum::PUBLIC_TYPE, '白名单时间过期');
            }
        }
    }

    /**
     * 超次数自动去白
     *
     * @return void
     */
    public function autoRemoveOverLimitWhite()
    {
        $switch = app('repo_erm_config')->getConfig(ErmEnum::ERM_SWITCH);
        if (!$switch) {
            return ;
        }

        $rule = app('repo_erm_config')->getConfig(ErmEnum::WHITE_LIMIT_NUM);
        if (!$rule) {
            return ;
        }
        $limitNum = (int)$rule->value;

        // 白名单风控超过次数
        $whiteList = app("model_erm_white_list")
            ->select('id', 'user_id')
            ->where('limit_num', '>', $limitNum)
            ->get();
        foreach ($whiteList as $k => $v) {
            $is_white = app('model_erm_public_list')->where(['user_id' => $v['user_id'], 'type' => ErmEnum::WHITE_TYPE])->first();
            if ($is_white) {
                app('repo_erm_public_list')->joinListWay($v['user_id'], ErmEnum::PUBLIC_TYPE, '超过风控次数');
            }
        }
    }

    /**
     * 触发风控的白名单用户
     *
     * @param array|int $userIds
     */
    public function triggerLimit($userIds)
    {
        $switch = app('repo_erm_config')->getConfig(ErmEnum::ERM_SWITCH);
        if (!$switch) {
            return ;
        }

        $rule = app('repo_erm_config')->getConfig(ErmEnum::WHITE_LIMIT_NUM);
        if (!$rule) {
            return ;
        }

        if (!is_array($userIds)) {
            $userIds = [$userIds];
        }
        app('model_erm_white_list')
            ->whereIn('user_id', $userIds)
            ->update([
                'limit_num' => DB::raw('limit_num+1')
            ]);
    }

    /**
     * 加入白名单
     *
     * @param [type] $param
     * @return mixed
     */
    public function join($param)
    {
        $user_id = app('model_user_data')->where('user_code', $param['user_code'])->value('user_id');
        if (!$user_id) {
            throw new BasicException(10001, '输入的用户编号有误，请重新输入');
        }
        $info = app('model_erm_public_list')->where(['user_id' => $user_id])->first();
        if ($info) {
            if ($info->type == ErmEnum::GRAY_TYPE) {
                throw new BasicException(10001, '该用户存在于灰名单中');
            }
            if ($info->type == ErmEnum::BLACK_TYPE) {
                throw new BasicException(10001, '该用户存在于黑名单中');
            }
        } else {
            //普通用户可以直接加入白名单
            app('repo_erm_public_list')->changeSyncToPublicList($user_id);
            $info = app('model_erm_public_list')->where(['user_id' => $user_id])->first();
        }
        $param['id'] = $info['id'];
        return app('repo_erm_public_list')->joinList($param);
    }

    /**
     * 白名单移除记录
     *
     * @param array $params
     * @param int $page
     * @param int $perPage
     * @return mixed
     */
    public function removeWhiteListLog($params, $page, $perPage)
    {
        $where = [];

        if (isset($params['user_code'])) {
            $where[] = ['t3.user_code', '=',  $params['user_code']];
        }

        if (isset($params['nickname'])) {
            $where[] = ['t3.nickname', '=',  $params['nickname']];
        }

        if (isset($params['user_type'])) {
            $where[] = ['t2.user_type', '=',  $params['user_type']];
        }

        if (isset($params['operator_id'])) {
            $where[] = ['t1.operator_id', '=',  $params['operator_id']];
        }

        if (isset($params['new_type'])) {
            $where[] = ['t1.new_type', '=',  $params['new_type']];
        }

        if (isset($params['register_start_time'])) {
            $where[] = ['t2.register_time', '>=',  strtotime($params['register_start_time'])];
        }

        if (isset($params['register_end_time'])) {
            $where[] = ['t2.register_time', '<=',  strtotime($params['register_end_time'])];
        }

        if (isset($params['remove_start_time'])) {
            $where[] = ['t1.create_time', '>=',  strtotime($params['remove_start_time'])];
        }

        if (isset($params['remove_end_time'])) {
            $where[] = ['t1.create_time', '<=',  strtotime($params['remove_end_time'])];
        }
        $fields = [
            't1.id',
            't1.user_id',
            't1.new_type',
            't1.operator_id',
            't1.create_time as remove_time',
            't1.remark',
            't2.user_type',
            't2.register_time',
            't3.user_code',
            't3.nickname',
            't4.admin_name'
        ];
        $recordModel = app('model_erm_list_record');
        $publicListModel = app("model_erm_public_list");
        $userDataModel = app('model_user_data');
        $adminModel = app('model_admin');

        $list = app('model_erm_list_record')
            ->from($recordModel->getTable() . " as t1")
            ->leftJoin(DB::raw($publicListModel->getTable() . " as t2"), "t1.user_id", "=", "t2.user_id")
            ->leftJoin(DB::raw($userDataModel->getTable() . " as t3"), "t1.user_id", "=", "t3.user_id")
            ->leftJoin(DB::raw($adminModel->getTable() . " as t4"), "t1.operator_id", "=", "t4.admin_id")
            ->where($where)
            ->where('t1.old_type', ErmEnum::WHITE_TYPE)
            ->select($fields)
            ->orderBy('t1.id', 'desc')
            ->paginate($perPage, ['*'], '', $page)
            ->toArray();

        $data = [];
        foreach ($list['data'] as $v) {
            $reason = $remark = '';

            if ($v['remark']) {
                if (strpos($v['remark'], ':') !== false) {
                    list($reason, $remark) = explode(':', $v['remark']);
                } elseif (strpos($v['remark'], '：') !== false) {
                    list($reason, $remark) = explode('：', $v['remark']);
                } else {
                    $remark = $v['remark'];
                }
            }
            $data[] = [
                'id' => $v['id'],
                'user_code' => $v['user_code'],
                'nickname' => $v['nickname'],
                'new_type' => $v['new_type'],
                'user_type' => $v['user_type'],
                'register_time' => date('Y-m-d H:i:s', $v['register_time']),
                'remove_time' => date('Y-m-d H:i:s', $v['remove_time']),
                'reason' => $reason,
                'remark' => $remark,
                'operator_id' => $v['operator_id'],
                'operator_name' => $v['admin_name'] ?? '',
            ];
        }

        return [
            'data' => $data,
            'total' => $list['total'],
        ];
    }
}
